import { obsUploader } from "@/utils/upload.js";

export default {
  data() {
    return {
      fileList: [],
      curFile: null
    };
  },
  methods: {
    beforeUpload(file) {
      const { basePath } = this.$attrs;
      file.status = "pending";
      file.percent = 0;
      // 覆盖默认的存储路径
      if (basePath) {
        const suffix = file.name.substring(file.name.lastIndexOf('.'));
        const timestamp = Date.now() + Math.round(Math.random() * 10000);
        file.key = basePath + timestamp + suffix;
      }
      this.curFile = file;
      this.fileList.push(file);
    },
    handleUpload({ file }) {
      const obs = obsUploader(this.$attrs.platform, this.$attrs.obsOptions);
      obs.startUpload(file);
      obs.onSuccess = (res) => {
        this.fileList = this.fileList.map((f) => {
          if (f.uid === file.uid) {
            f.percent = 100;
            f.status = "success";
          }
          return f;
        });
        this.curFile = null;
      };
      obs.onError = (file, error) => {
        if (!this.curFile) return;
        this.fileList = this.fileList.map((f) => {
          if (f.uid === this.curFile.uid) {
            f.status = "fail";
            f.error = error ? error.msg : "上传失败";
          }
          return f;
        });
        this.curFile = null;
      };
      obs.onProgress = (file, percent) => {
        this.fileList = this.fileList.map((f) => {
          if (f.uid === file.uid) {
            f.percent = percent;
            f.status = "uploading";
          }
          return f;
        });
      };
    },
    handleRemove(file) {
      this.fileList = this.fileList.filter((f) => f.uid !== file.uid);
      this.$emit("remove", file, this.fileList);
    }
  }
};
